package com.platform.data.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.base.domain.CollectorInfo;
import com.platform.base.domain.MeterInfo;
import com.platform.base.mapper.CollectorInfoMapper;
import com.platform.base.mapper.MeterInfoMapper;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.netty.NettyUtil;
import com.platform.common.utils.rabbit.RabbitUtils;
import com.platform.common.utils.redis.RedisRun;
import com.platform.common.utils.redis.RedisUtil;
import com.platform.data.domain.HeatYear;
import com.platform.data.mapper.HeatYearMapper;
import com.platform.data.service.IHeatYearService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 热采集数据Service业务层处理
 * 
 * @author wangqi
 * @date 2020-09-27
 */
@Service
public class HeatYearServiceImpl extends ServiceImpl<HeatYearMapper,HeatYear> implements IHeatYearService
{
    @Autowired
    private HeatYearMapper heatYearMapper;

    @Autowired
    private MeterInfoMapper meterInfoMapper;
    @Autowired
    private CollectorInfoMapper collectorInfoMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RabbitUtils rabbitUtils;

    /**
     * 查询热采集数据列表
     * 
     * @param heatYear 热采集数据
     * @return 热采集数据
     */
    @Override
    public List<HeatYear> selectHeatYearList(HeatYear heatYear)
    {
        return heatYearMapper.selectHeatYearList(heatYear);
    }




    /**
     * 新增热采集数据
     * 
     * @param heatYear 热采集数据
     * @return 结果
     */
    @Override
    public int insertHeatYear(HeatYear heatYear)
    {
        heatYear.setCreateTime(DateUtils.getNowDate());
        return heatYearMapper.insert(heatYear);
    }

    /**
     * 读取热表数据
     * @param locationId 热表信息
     * @return
     * @throws Exception
     */
    @Override
    public String checkData(String locationId) throws InterruptedException {
        int failureNum = 0;
        int successNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder successMsg = new StringBuilder();
        List<MeterInfo> infoList = meterInfoMapper.selectMeterInfoBylocationId(locationId);
        for(MeterInfo info : infoList){
            String meterId = info.getMeterId();

            if(info.getCollectorId() == null || info.getCollectorId().equals("")){
                return "热表 " + info.getMeterId() + " 未关联采集器";
            }


            //判断采集器是否在线
            boolean status = redisUtil.hHasKey("sys-netty", info.getCollectorId());
            if(!status){
                CollectorInfo cinfo = collectorInfoMapper.selectCollectorInfoById(info.getCollectorId());
                cinfo.setOnlineStatus(Integer.valueOf(0));
                cinfo.setCollectorId(info.getCollectorId());
                collectorInfoMapper.updateById(cinfo);
                return "热表 " + info.getMeterId() + "关联的采集器" + info.getCollectorId() + " 已离线";
            }
            //获取采集器高位
            String cenhigh = info.getCollectorId().substring(0,2);
            //获取采集器低位
            String cenlow = info.getCollectorId().substring(2,4);

            String add3 = info.getMeterId().substring(0,2);
            String add4 = info.getMeterId().substring(2,4);
            String add5 = info.getMeterId().substring(4,6);
            String add6 = info.getMeterId().substring(6,8);
            //控制码
            String cont = "01";
            //计算校验码
            int ll = NettyUtil.get10HexNum(cenhigh)+NettyUtil.get10HexNum(cenlow)+NettyUtil.get10HexNum(add3)+NettyUtil.get10HexNum(add4)
                    +NettyUtil.get10HexNum(add5)+NettyUtil.get10HexNum(add6)+NettyUtil.get10HexNum(cont)+NettyUtil.get10HexNum(info.getFactory().getFactoryCode());
            String check = NettyUtil.get16HexNum(ll);
            if(check.length()<2){
                check = "0" + check;
            }else{
                check = check.substring(check.length()-2);
            }
            String response = "AA "+ cenlow +" "+ cenhigh + " " + add3 + " " + add4 + " " + add5 + " " + add6 + " " + cont + " " + info.getFactory().getFactoryCode() + " 00 00 00 00 00 " + check + " FF ";
            String responseStr = response.replace(" ", "");
            rabbitUtils.writeToClient(info.getCollectorId(), responseStr, "热表"+meterId+"数据采集");
            CountDownLatch countDownLatch = new CountDownLatch(1);
            new Thread(new RedisRun(countDownLatch, redisUtil, meterId, cont)).start();
            countDownLatch.await();
            String result = RedisRun.result;
            if(result.equals("00")){
                successNum++;
                successMsg.append("<br/>" + successNum + "、热表 " + info.getMeterId() + " 采集成功");
            }else{
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、热表 " + info.getMeterId() + " 采集失败");
            }
        }
        if(failureNum>0){
            failureMsg.insert(0, "很抱歉，热表采集失败！共 " + failureNum + " 条数热表采集失败，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }else{
            successMsg.insert(0, "恭喜您，热表已全部采集成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
